package com.lkd.shoppingcart.web;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.lkd.shoppingcart.entity.Admin;
import com.lkd.shoppingcart.entity.Cart;
import com.lkd.shoppingcart.entity.OrdersView;
import com.lkd.shoppingcart.entity.User;
import com.lkd.shoppingcart.service.AdminService;
import com.lkd.shoppingcart.service.CartService;
import com.lkd.shoppingcart.service.OrderService;
import com.lkd.shoppingcart.service.UserService;
import com.lkd.shoppingcart.service.impl.AdminServiceImpl;
import com.lkd.shoppingcart.service.impl.CartServiceImpl;
import com.lkd.shoppingcart.service.impl.OrderServiceImpl;
import com.lkd.shoppingcart.service.impl.UserServiceImpl;
import com.lkd.shoppingcart.utils.WebUtils;

@WebServlet("/userServlet")
public class UserServlet extends BaseServlet {

	private static final long serialVersionUID = 1L;
	private UserService userService = new UserServiceImpl();
	private AdminService adminService = new AdminServiceImpl();
	private CartService cartService = new CartServiceImpl();
	private OrderService orderService = new OrderServiceImpl();

	/**
	 * 检查用户名是否已存在
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        boolean existsUsername = userService.existsUsername(username);
        
        // 返回用户名是否已存在
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("existsUsername", existsUsername);

        Gson gson = new Gson();
        String json = gson.toJson(resultMap);

        resp.getWriter().write(json);
    }
    
    /**
     * 登录
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        
        User loginUser = userService.login(new User(null, username, password));
        
        // 如果等于null,说明登录失败
        if (loginUser == null) {
            // 把错误信息，和回显的表单项信息，保存到Request域中
            req.setAttribute("msg", "用户或密码错误！");
            req.setAttribute("username", username);
            
            // 跳回登录页面
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
        } else {
            // 登录成功
        	HttpSession session = req.getSession();
        	Cart cart = cartService.queryByUserId(loginUser.getId());
        	List<OrdersView> ordersViewList = orderService.queryByUserId(loginUser.getId());
        	
        	session.setAttribute("user", loginUser);
        	session.setAttribute("cart", cart);
        	session.setAttribute("ordersViewList", ordersViewList);
        	session.setAttribute("productsCount", cartService.queryForCount(loginUser.getId()));
        	
        	// 检查登录用户是否为管理员
        	Admin loginAdmin = adminService.login(new Admin(loginUser.getId(), username, password));
    	    if (loginAdmin != null) {
    	    	session.setAttribute("admin", loginAdmin);
            }
            
            // 跳到登录成功页面
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req, resp);
        }
    }
    
    /**
     * 退出登录
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	// 销毁Session
        req.getSession().invalidate();
        
        // 重定向到首页
        resp.sendRedirect(req.getContextPath());
    }

    /**
     * 注册
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取Session中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        
        // 删除 Session中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

        // 获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");

        User user = WebUtils.copyParamToBean(req.getParameterMap(), new User());

        // 检查验证码是否正确
        if (token!=null && token.equalsIgnoreCase(code)) {
            // 检查用户名是否可用
            if (userService.existsUsername(username)) {
                System.out.println("用户名[" + username + "]已存在!");
                req.setAttribute("msg", "用户名已存在！！");
                req.setAttribute("username", username);
                req.setAttribute("email", email);

                // 跳回注册页面
                req.getRequestDispatcher("/pages/user/register.jsp").forward(req, resp);
            } else {
                userService.registerUser(new User(null, username, password));
                
                // 跳到注册成功页面
                req.getRequestDispatcher("/pages/user/register_success.jsp").forward(req, resp);
            }
        } else {
            req.setAttribute("msg", "验证码错误！！");
            req.setAttribute("username", username);
            req.setAttribute("email", email);
            
            System.out.println("验证码[" + code + "]错误");
            req.getRequestDispatcher("/pages/user/register.jsp").forward(req, resp);
        }

    }
	
}
